package com.feihong.yw189.activity.kuandai;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.KeyboardUtils;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.activity.kaika.KaiKaActivity;
import com.feihong.yw189.adapter.Kuandai.BaoZhuangAdapter;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.dialog.DetermineDialog;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.Kaika.BaoZhuangModel;
import com.feihong.yw189.model.Kaika.YanZhengAdressBaoZhuangModel;
import com.holenzhou.pullrecyclerview.BaseRecyclerAdapter;
import com.holenzhou.pullrecyclerview.PullRecyclerView;
import com.holenzhou.pullrecyclerview.layoutmanager.XLinearLayoutManager;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 报装地址
 */

public class BaoZhuangAddressActivity extends BaseActivity {

    @BindView(R.id.rl_goback)
    RelativeLayout rlGoBack;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.et_input)
    EditText minput;
    @BindView(R.id.iv_search)
    ImageView msearchtxt;
    String getInput;

    @BindView(R.id.pull_recycler_view)
    PullRecyclerView mPullRecyclerView;

    BaoZhuangAdapter mAdapter;
    List<BaoZhuangModel.DataBean.ListBean> mDataList;
    int pageSize = 1;
    MyUsualyDialog myUsualyDialog;

    @BindView(R.id.null_data_layout_txt)
    TextView mNullDataWarningTv;
    @BindView(R.id.null_data_layout)
    RelativeLayout mNullDataLayout;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectNetErrorLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choosesim);
        ButterKnife.bind(this);

        initView();
        bindData();
    }

    @Override
    public void setTheme() {

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    private void initView() {
        mNullDataWarningTv.setText("暂无对应条件的地址");
        txtPagetitle.setText("报装地址");
        ivLin.setVisibility(View.GONE);
        minput.setHint("请输入地址关键字");
        minput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
        msearchtxt.setBackgroundResource(R.mipmap.ivsearchaddress);
        myUsualyDialog = new MyUsualyDialog(BaoZhuangAddressActivity.this, R.layout.wait_item);
    }

    public void bindData() {
        mDataList = new ArrayList<>();

        // 初始化PullRecyclerView
        mPullRecyclerView.setLayoutManager(new XLinearLayoutManager(this));
        mAdapter = new BaoZhuangAdapter(this, R.layout.item_baozhuang, mDataList);
        mPullRecyclerView.setAdapter(mAdapter);

        mPullRecyclerView.setColorSchemeResources(R.color.appBlue); // 设置下拉刷新的旋转圆圈的颜色
        mPullRecyclerView.enablePullRefresh(true); // 开启下拉刷新，默认即为true，可不用设置
        mPullRecyclerView.enableLoadDoneTip(false, R.string.load_done_tip); // 开启数据全部加载完成时的底部提示，默认为false
        mPullRecyclerView.enableLoadMore(false);
        //刷新监听
        mPullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {

                getInput = minput.getText().toString().trim().replaceAll("\n", "");
                mAdapter.clear();
                App.getApp().getHttpTools().getBaozhuang(getInput, CallBackUp);
            }

            @Override
            public void onLoadMore() {
            }
        });
        // 通过adapter设置item的点击事件
        mAdapter.setOnRecyclerItemClickListener(new BaseRecyclerAdapter.OnRecyclerItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {
                if (!myUsualyDialog.isShowing()) {
                    myUsualyDialog.show();
                }
                App.getApp().getHttpTools().getYanZhengAdress(mDataList.get(position).getAcc_type(), mDataList.get(position).getSegm_id(), new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        if (activityIsDestory()) {
                            return;
                        }
                        if (myUsualyDialog != null && myUsualyDialog.isShowing()) {
                            myUsualyDialog.dismiss();
                        }
                        try {
                            YanZhengAdressBaoZhuangModel yanzhengModel = JSON.parseObject(result, YanZhengAdressBaoZhuangModel.class);
                            if (yanzhengModel.getStatus() == 1) {
                                Intent mIntent = new Intent();
                                Bundle bundle = new Bundle();
                                bundle.putString("Acc_type", mDataList.get(position).getAcc_type());
                                bundle.putString("Segm_id", mDataList.get(position).getSegm_id());
                                bundle.putString("Stand_name", mDataList.get(position).getStand_name());
                                mIntent.putExtras(bundle);
                                mIntent.setClass(BaoZhuangAddressActivity.this, KaiKaActivity.class);
                                setResult(RESULT_OK, mIntent);
                                finish();
                            } else if (yanzhengModel.getStatus() == 0) {
                                DetermineDialog toSetBtDialog = new DetermineDialog(BaoZhuangAddressActivity.this,
                                        mDataList.get(position).getAcc_type(), mDataList.get(position).getSegm_id(), mDataList.get(position).getStand_name()
                                );
                                if (toSetBtDialog != null) {
                                    toSetBtDialog.show();
                                }
                            }
                        } catch (Exception ex) {
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                        if (activityIsDestory()) {
                            return;
                        }
                        if (myUsualyDialog != null && myUsualyDialog.isShowing()) {
                            myUsualyDialog.dismiss();
                        }
                        showToast(getResources().getString(R.string.connect_sever_error_toast));
                    }

                    @Override
                    public void onCancelled(Callback.CancelledException cex) {
                    }

                    @Override
                    public void onFinished() {

                    }
                });

            }
        });
    }


    private void noDataLayout() {
        if (mNullDataLayout.getVisibility() == View.GONE) {
            mPullRecyclerView.setVisibility(View.GONE);
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.VISIBLE);
        }
    }

    private void connectNetErrorLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.GONE) {
            mPullRecyclerView.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.GONE);
            mConnectNetErrorLayout.setVisibility(View.VISIBLE);
        }
    }

    private void normalLayout() {
        if (mConnectNetErrorLayout.getVisibility() == View.VISIBLE || mNullDataLayout.getVisibility() == View.VISIBLE) {
            mConnectNetErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.GONE);
            mPullRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.rl_goback, R.id.iv_search,R.id.requery_data_tv})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.rl_goback:
                finish();
                break;
            case R.id.iv_search:
                //搜索号码
                getInput = minput.getText().toString().trim().replaceAll("\n", "");
                KeyboardUtils.hideSoftInput(getActivity());
                if (!TextUtils.isEmpty(getInput)) {
                    normalLayout();
                    mPullRecyclerView.autoRefresh();
                } else {
                    showToast("请输入关键字");
                }
                break;
            case R.id.requery_data_tv:
                normalLayout();
                mPullRecyclerView.autoRefresh();
                break;
            default:
                break;
        }
    }

    RequestCallBack<String> CallBackUp = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            if (activityIsDestory()) {
                return;
            }
            //json解析
            try {
                BaoZhuangModel baoZhuangModel = JSON.parseObject(result, BaoZhuangModel.class);

                if (baoZhuangModel.getStatus() == 1) {
                    //list解析
                    List<BaoZhuangModel.DataBean.ListBean> mListBean = baoZhuangModel.getData().getList();
                    if (mListBean == null || mListBean.size() == 0) {
                        noDataLayout();
                        return;
                    }
                    normalLayout();
                    BaoZhuangModel.DataBean.ListBean model;
                    for (BaoZhuangModel.DataBean.ListBean message : baoZhuangModel.getData().getList()) {
                        model = new BaoZhuangModel.DataBean.ListBean();
                        model.setAcc_type(message.getAcc_type());
                        model.setSegm_id(message.getSegm_id());
                        model.setStand_name(message.getStand_name());
                        mDataList.add(model);
                    }
                    mAdapter.addAll(mDataList);
                } else {
                    noDataLayout();
                    showToast(baoZhuangModel.getInfo());
                }
            } catch (Exception ex) {
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (activityIsDestory()) {
                return;
            }
            connectNetErrorLayout();
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
        }

        @Override
        public void onFinished() {

            if (activityIsDestory()) {
                return;
            }
            mPullRecyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPullRecyclerView.stopRefresh();
                }
            }, 200);
        }
    };

}

